package com.wfh.wfhwx.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wfh.wfhwx.common.BaseResponse;
import com.wfh.wfhwx.common.ResultUtils;
import com.wfh.wfhwx.exception.BusinessException;
import com.wfh.wfhwx.exception.ErrorCode;
import com.wfh.wfhwx.exception.ThrowUtils;
import com.wfh.wfhwx.model.dto.WxReplyRuleAddRequest;
import com.wfh.wfhwx.model.dto.WxReplyRulePageQueryRequest;
import com.wfh.wfhwx.model.dto.WxReplyRuleUpdateRequest;
import com.wfh.wfhwx.model.entity.WxReplyRule;
import com.wfh.wfhwx.model.enums.WxReplyRuleTypeEnum;
import com.wfh.wfhwx.model.vo.WxReplyRuleVO;
import com.wfh.wfhwx.service.UserService;
import com.wfh.wfhwx.service.WxReplyRuleService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import me.chanjar.weixin.common.service.WxService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * @Title: WxReplyRuleController
 * @Author wangfenghuan
 * @Package com.wfh.wfhwx.controller
 * @Date 2025/6/20 16:25
 * @description: 公众号回复规则接口
 */
@RestController
@RequestMapping("/wx/reply")
public class WxReplyRuleController {

    private final WxService wxService = new WxMpServiceImpl();

    @Resource
    private WxReplyRuleService wxReplyRuleService;

    @Resource
    private UserService userService;

    /**
     * 新增回复功能
     *
     * @param wxReplyRuleAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @Operation(summary = "添加回复规则")
    public BaseResponse<Long> addWxRelyRule(
            @Valid @RequestBody WxReplyRuleAddRequest wxReplyRuleAddRequest,
            HttpServletRequest request
    ) {
        // 校验参数
        if (ObjectUtils.isEmpty(wxReplyRuleAddRequest)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Integer replyType = wxReplyRuleAddRequest.getReplyType();
        // 当为菜单类型的时候
        if (ObjectUtils.equals(replyType, WxReplyRuleTypeEnum.getValues())) {
            ThrowUtils.throwIf(
                    StringUtils.isBlank(wxReplyRuleAddRequest.getEventKey()),
                    ErrorCode.PARAMS_ERROR, "菜单类型的时候，eventKey不能为空"
            );
            ThrowUtils.throwIf(wxReplyRuleService.lambdaQuery()
                    .eq(WxReplyRule::getEventKey, wxReplyRuleAddRequest.getEventKey())
                    .eq(WxReplyRule::getAppId, wxReplyRuleAddRequest.getAppId())
                    .exists(), ErrorCode.PARAMS_ERROR, "菜单类型的时候，eventKey不能重复");

        }
        // 校验关键字
        ThrowUtils.throwIf(Objects.equals(replyType, WxReplyRuleTypeEnum.KEYWORDS.getValue()) &&
                ObjectUtils.isEmpty(wxReplyRuleAddRequest.getMatchValue()), ErrorCode.PARAMS_ERROR, "关键字类型的时候，matchValue不能为空");
        WxReplyRule wxReplyRule = wxReplyRuleAddRequest.toWxReplyRule();
        wxReplyRule.setUserId(userService.getLoginUser(request).getId());
        wxReplyRuleService.save(wxReplyRule);
        return ResultUtils.success(wxReplyRule.getId());
    }

    /**
     * 更新回复规则
     *
     * @param wxReplyRuleUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @Operation(summary = "更新回复规则")
    public BaseResponse<Boolean> updateWxRelyRule(@RequestBody WxReplyRuleUpdateRequest wxReplyRuleUpdateRequest) {
        // 参数校验
        if (ObjectUtils.isEmpty(wxReplyRuleUpdateRequest)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }

        // 判断是否要修改菜单栏点击事件的key
        WxReplyRule wxReplyRule = wxReplyRuleService.getById(wxReplyRuleUpdateRequest.getId());
        if (ObjectUtils.notEqual(wxReplyRule.getReplyType(), WxReplyRuleTypeEnum.getValues())) {
            // 判断是否已经被使用过
            String appId = wxReplyRuleUpdateRequest.getAppId();
            ThrowUtils.throwIf(wxReplyRuleService.count(Wrappers.lambdaQuery(WxReplyRule.class)
                            .eq(WxReplyRule::getEventKey, wxReplyRuleUpdateRequest.getEventKey())
                            .eq(WxReplyRule::getAppId, StringUtils.isBlank(appId) ? wxReplyRule.getAppId() : appId)) > 0,
                    ErrorCode.PARAMS_ERROR, "菜单类型的时候，eventKey不能重复");
        }
        return ResultUtils.success(wxReplyRuleService.updateById(wxReplyRuleUpdateRequest.toWxReplyRule()));
    }

    /**
     * 分页查询回复规则
     *
     * @param wxReplyRulePageQueryRequest 分页查询请求
     * @return 回复规则分页数据
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询回复规则")
    public BaseResponse<Page<WxReplyRuleVO>> listWxMpReplyRuleByPage(WxReplyRulePageQueryRequest wxReplyRulePageQueryRequest) {
        long current = wxReplyRulePageQueryRequest.getCurrent();
        long size = wxReplyRulePageQueryRequest.getPageSize();
        return ResultUtils.success(wxReplyRuleService.getPage(new Page<>(current, size),
                wxReplyRuleService.getQueryWrapper(wxReplyRulePageQueryRequest)));
    }

    /**
     * 根据ID查询回复规则详情
     *
     * @param id 规则ID
     * @return 回复规则详情
     */
    @GetMapping("/get/vo")
    @Operation(summary = "回复规则详情")
    public BaseResponse<WxReplyRuleVO> getWxMpReplyRuleVOById(Long id) {
        // 查询规则
        WxReplyRule wxReplyRule = wxReplyRuleService.getById(id);

        // 验证规则是否存在
        ThrowUtils.throwIf(ObjectUtils.isEmpty(wxReplyRule), ErrorCode.NOT_FOUND_ERROR);

        // 转换为 VO
        WxReplyRuleVO replyRuleVO = WxReplyRuleVO.obj2VO(wxReplyRule);

        // 添加创建者信息
        replyRuleVO.setUser(userService.getUserVO(userService.getById(wxReplyRule.getUserId())));
        return ResultUtils.success(replyRuleVO);
    }

}
